<template>
    <div class="date-range-wrap">
        <el-date-picker
            class="el-date-cus"
            v-model="data"
            type="daterange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="~"
            :start-placeholder="props.startPlaceHolder"
            :end-placeholder="props.endPlaceHolder"
            :default-time="defaultTime"
            @visible-change="visibleChange"
        />
    </div>
</template>

<script setup>
import { ref, defineExpose, onMounted, defineProps } from 'vue';
import Dayjs from 'dayjs';

const props = defineProps({
    isTimeStamp: { // 是否返回时间戳格式 否返回YYYY-MM-DD HH:mm:ss格式
        type: Boolean,
        default: false
    },
    startPlaceHolder: {
        type: String,
        default: '请选择开始日期'
    },
    endPlaceHolder: {
        type: String,
        default: '请选择结束日期'
    }
})

let data = ref('');

const formetTime = (date) => {
    let y = date.getFullYear();
	let m = date.getMonth() + 1;
	m = m < 10 ? '0' + m : m;
	let d = date.getDate();
	d = d < 10 ? '0' + d : d;
	let h = date.getHours();
	h = h < 10 ? '0' + h : h;
	let minute = date.getMinutes();
	minute = minute < 10 ? '0' + minute : minute;
	let second = date.getSeconds();
	second = second < 10 ? '0' + second : second;
	return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

// 指定起始日期和结束日期的默认时间。
const defaultTime = ref([
   new Date(2000, 1, 1, 0, 0, 0),
   new Date(2000, 2, 1, 23, 59, 59)
])

// 获取日期范围
const getDateRange = () => {
    console.log(data.value);
    // 秒级和毫秒级时间戳
    // console.log(Dayjs(data.value[0]).unix(), Dayjs(data.value[0]).valueOf());
    if (data.value && data.value.length === 2) {
        if (props.isTimeStamp) {
            let startTime = Dayjs(data.value[0]).valueOf();
            let endTime = Dayjs(data.value[1]).valueOf();
            return { startTime, endTime }
        } else {
            return { startTime: data.value[0], endTime: data.value[1] }
        }
    } else {
        return { startTime: '', endTime: '' }
    }
}

// 清空日期范围
const resetDateRange = () => {
    data.value = '';
}

// 如果没有任何日期，则把class置空
const visibleChange = (isVisible) => {

   if(!isVisible && !data.value) {
       let list = document.querySelectorAll('.in-range');
       list?.length && list.forEach(item => {
          item.classList.remove('in-range');
       })
       if(document.querySelector('.start-date')){
           document.querySelector('.start-date').classList.remove('start-date');
       }
       if(document.querySelector('.end-date')){
           document.querySelector('.end-date').classList.remove('end-date');
       }
   }
}

// 清空时间范围
onMounted(() => {
    resetDateRange();
});

defineExpose({
    getDateRange,
    resetDateRange
})
</script>

<style lang="scss" scoped>
.date-range-wrap {
    display: flex;
}
</style>